//
//  PolicyViewController.m
//  阿帕
//
//  Created by mac on 2020/1/6.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "PolicyViewController.h"
#import "PolicyCell.h"
#import "ElectronDetailViewController.h"
#import "PolicySearchViewController.h"

@interface PolicyViewController ()<UITableViewDataSource, UITableViewDelegate, PolicySearchConditionDelegate>

@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (strong , nonatomic)NSDictionary *searchDic;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation PolicyViewController

static const CGFloat cellHeight = 230;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    [self setupBaseView];
    
}

- (void)setupBaseView {
    
    self.navigationItem.title = @"保单列表";

    self.view.backgroundColor = BackgroundColor;
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    //默认按钮为蓝色  设置按钮为自己本身图片的颜色
    [searchButton setImage:[[UIImage imageNamed:@"gcy_icon_search_siji"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [searchButton setTitleColor:Dark_TextColor forState:UIControlStateNormal];
    [searchButton addTarget:self action:@selector(rightBarItemClick:) forControlEvents:UIControlEventTouchUpInside];
        
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:searchButton];
    rightItem.imageInsets = UIEdgeInsetsMake(0, -15,0, 0);//设置向左偏移
    self.navigationItem.rightBarButtonItem = rightItem;

 
//    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 40)];
//    _textFiled.font = font(14);
//    _textFiled.text = @"";
//    _textFiled.backgroundColor = [UIColor whiteColor];
//    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
//    _textFiled.keyboardType = UIKeyboardTypeDefault;
//    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请填写查询条件" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
//    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
//
//    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 20, 40)];
//    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 40)];
//    _textFiled.leftViewMode = UITextFieldViewModeAlways;
//    [_textFiled addSubview: leftView];
    
    
//    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
//    searchImage.userInteractionEnabled = YES;
//    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
//    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
//    _textFiled.rightViewMode = UITextFieldViewModeAlways;
//    [_textFiled addSubview:searchImage];
//
//    [searchImage nyl_addTapGes:^{
//        [self contractListRequest];
//    }];
//
//    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];

    [self policyListRequest];
}

- (void)rightBarItemClick:(UIButton *)button {
    PolicySearchViewController *psvc = [[PolicySearchViewController alloc] init];
    psvc.delegate = self;
    [self.navigationController pushViewController:psvc animated:YES];
}

- (void)GetSearchConditionResult:(NSDictionary *)dictionary {
    _searchDic = dictionary;
    [self policyListRequest];
}

- (void)policyListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params;
    
    if ([DCSpeedy isBlankDictionary:_searchDic] == NO) {
        params = @{
            @"pageSize":DEFULT_LOAD_NUM,
            @"pageNum":[NSNumber numberWithInteger:_pageNum],
            @"mainOrderNumber": _searchDic[@"mainOrderNumber"],//货源单号
            @"orderDetailNumber": _searchDic[@"orderDetailNumber"],//运输单号
            @"applyPolicyNo": _searchDic[@"applyPolicyNo"],//保单号
            @"gmtCreatedStart": _searchDic[@"gmtCreatedStart"],//保险起期
            @"gmtCreatedEnd": _searchDic[@"gmtCreatedEnd"],//保险止期
            @"shipmentInfo": _searchDic[@"shipmentInfo"],//货主信息
            @"driverInfo": _searchDic[@"driverInfo"],//司机信息
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        };
    } else {
        params = @{
            @"pageSize":DEFULT_LOAD_NUM,
            @"pageNum":[NSNumber numberWithInteger:_pageNum],
            @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
//            @"mainOrderNumber": @"",//货源单号
//            @"orderDetailNumber": @"",//运输单号
//            @"applyPolicyNo": @"",//保单号
//            @"insuranceBeginTime": @"",//保险起期
//            @"insuranceEndTime": @"",//保险止期
//            @"shipmentInfo": @"",//货主信息
//            @"driverInfo": @"",//司机信息
        };
    }
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], OPENINSURE) withParameter:params withVC:self netName:@"保单列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            [weakSelf.dataArray addObjectsFromArray:[PolicyRecordModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];

            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;

        } else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }

            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];

        }

        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    _searchDic = nil;
    [self policyListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self policyListRequest];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PolicyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = self.dataArray[indexPath.row];
    
    return cell;
    
}



#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PolicyRecordModel *model = self.dataArray[indexPath.row];
    if ([DCSpeedy isBlankString:model.openInsurePDF] == YES) {
        [XSInfoView showInfo:@"暂无保单" onView:self.view];
        return;
    }
    ElectronDetailViewController *edvc = [[ElectronDetailViewController alloc] init];
    edvc.contractPath = model.openInsurePDF;
    edvc.pageTitle = @"保单详情";
    [self.navigationController pushViewController:edvc animated:YES];
    
}
    
#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 5, ScreenW, ScreenH - NavHeight - 5);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([PolicyCell class]) bundle:nil] forCellReuseIdentifier:@"CellID"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.center = self.view.center;
        _foundImageView.cy_centerY -= 50;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

@end
